#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "LogMessage.hpp"
#include "Err.hpp"


const int backlog = 128;
static const int defaultfd = -1;

class Sock
{
public:
    Sock():sock_(defaultfd)
    {}
    ~Sock()
    {
        if(sock_ != defaultfd)
            close(sock_);
    }
public:
    void Socket()//创建套接字
    {
        sock_ = socket(AF_INET, SOCK_STREAM, 0);
        if(sock_ < 0)
        {
            logMessage(FATAL, "sock create error!");
            exit(SOCK_ERR);
        }
    }
    bool Bind(uint16_t port)//绑定
    {
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(sock_, (struct sockaddr *)&local, sizeof(local)) != 0) return false;
        return true;
    }
    bool Listen()//监听
    {
        if (listen(sock_, backlog) != 0)
        {
            return false;
        }
        return true;
    }
    int Accept(std::string *clientip, uint16_t *clientport, int* err)//获取
    {
        struct sockaddr_in client;
        socklen_t clientlen = sizeof(client);
        int sock = accept(sock_, (struct sockaddr *)&client, &clientlen);
        *err = errno;
        *clientip = inet_ntoa(client.sin_addr);
        *clientport = client.sin_port;
        
        return sock;
    }
    int FD()
    {
        return sock_;
    }
    void Close()
    {
        if(sock_ != defaultfd)
            close(sock_);
    }
public:
    int sock_;
};